﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using NetMQ;
using NetMQ.Sockets;

namespace NetMQ_Router
{
    class Program
    {
        public static void Main(string[] args)
        {


            Console.WriteLine("Msg Server Is Runing!!!");

            using (var server = new RouterSocket("@tcp://127.0.0.1:5556"))
            {
                // server loop
                while (true)
                {
                    var clientMessage = server.ReceiveMultipartMessage();

                    Console.WriteLine(" INCOMING CLIENT MESSAGE FROM CLIENT ");

                    PrintFrames("Server receiving", clientMessage);
                    if (clientMessage.FrameCount == 2)
                    //服务端发送回复
                    {
                        var clientAddress = clientMessage[0];
                        Console.WriteLine($"Client Add Is:{clientAddress.ConvertToString()}");
                        var clientOriginalMessage = clientMessage[1].ConvertToString();
                        //Console.WriteLine($"{clientOriginalMessage}");
                        string response = string.Format("{0} back from server {1}",
                            clientOriginalMessage, DateTime.Now.ToLongTimeString());
                        Console.WriteLine($"response Is : {response}");
                        var messageToClient = new NetMQMessage();
                        messageToClient.Append(clientAddress);
                        messageToClient.AppendEmptyFrame();
                        messageToClient.Append(response);
                        server.SendMultipartMessage(messageToClient);
                    }
                }
            }



        }

       static void PrintFrames(string operationType, NetMQMessage message)
        {
            for (int i = 0; i < message.FrameCount; i++)
            {

                Console.WriteLine($"{operationType} Socket : Frame[{i}] = {message[i].ConvertToString()}");
            }
        }

       
    }
}
